package tr.helper.service;

import static cn.hutool.core.util.CharsetUtil.CHARSET_UTF_8;

import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import tr.helper.CommonUtil;
import tr.helper.service.jx.jiuxian;

/**
 * tr-service
 *
 * @author MrYe
 * @date 2022-01-21 14:51
 */
public class JiuxianService {

    public static final String host = "https://login.jiuxian.com";

    public static final String CAPTCHA_CODE_PATH = "/public/captchaimg.htm";

    public static final String LOGIN_PATH = "/login.htm";

    public static final String CART_PATH = "/orderset/settlement.htm";

    public HttpResponse getImage() {
        final HttpRequest request = HttpUtil.createGet(host + CAPTCHA_CODE_PATH + "?timestamp=" + RandomUtil.randomInt(1000, 9999));
        return request.execute();
    }

    public HttpResponse login(String username, String password) {
        final String newLoginUrl = "https://newappuser.jiuxian.com/user/loginUserNamePassWd.htm";

        final HttpRequest request = HttpUtil.createPost(newLoginUrl);

        request.body(
            "apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=2717&channelCode=0,1&cityName=上海市cpsId=appstore&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.31619411892361&longi=121.4094590928819&netEnv=unkown&passWord="
                + password + "&supportWebp=1&sysVersion=13.6.1&token=&userName=" + username);

        return request.execute();
    }

    public HttpResponse getAddress(String token) {
        String url = "https://newappuser.jiuxian.com/address/getAddressList.htm?token=" + token;
        final HttpRequest request = HttpUtil.createGet(url);
        return request.execute();
    }

    /**
     * 预约接口
     *
     * @param query
     * @return
     */
    public HttpResponse addPre(String query) {
        final String preUrl = "https://newappuser.jiuxian.com/reservation/preReservation.htm?" + query;

        final HttpRequest request = HttpUtil.createGet(preUrl);
        request.header("User-Agent", "jiuxian/9.0.10 (iPhone; iOS 13.6.1; Scale/2.00)");
        request.header("Host", "newappuser.jiuxian.com");
        return request.execute();
    }

    /**
     * 预约接口
     *
     * @param query
     * @return
     */
    public HttpResponse addPreOrder(String query) {
        final String preUrl = "https://newappuser.jiuxian.com/reservation/preReservationOrder.htm?" + query;

        final HttpRequest request = HttpUtil.createGet(preUrl);
        request.header("User-Agent", "jiuxian/9.0.10 (iPhone; iOS 13.6.1; Scale/2.00)");
        request.header("Host", "newappuser.jiuxian.com");
        return request.execute();
    }

    public HttpResponse addCart(String query) {
        final String newSettlementUrl = "https://newapporder.jiuxian.com/orderset/settlement.htm";

        final HttpRequest request = HttpUtil.createPost(newSettlementUrl);
        request.header("User-Agent", "jiuxian/9.0.10 (iPhone; iOS 13.6.1; Scale/2.00)");
        request.header("Host", "newapporder.jiuxian.com");
        request.body(URLEncoder.createQuery().encode(query, CHARSET_UTF_8));
        return request.execute();
    }

    public HttpResponse makeOrder(String query) {
        final String newSettlementUrl = "https://newapporder.jiuxian.com/orderset/addorder.htm";

        final HttpRequest request = HttpUtil.createPost(newSettlementUrl);
        request.header("User-Agent", "jiuxian/9.0.10 (iPhone; iOS 13.6.1; Scale/2.00)");
        request.header("Host", "newapporder.jiuxian.com");
        request.body(URLEncoder.createQuery().encode(query, CHARSET_UTF_8));
        return request.execute();
    }

    public HttpResponse makeSpecialOrder(String query) {
        final String newSettlementUrl = "https://newapprerorder.jiuxian.com/reservation/addorder.htm";

        final HttpRequest request = HttpUtil.createPost(newSettlementUrl);
        request.header("User-Agent", "jiuxian/9.0.10 (iPhone; iOS 13.6.1; Scale/2.00)");
        request.header("Host", "newapprerorder.jiuxian.com");
        request.body(URLEncoder.createQuery().encode(query, CHARSET_UTF_8));
        return request.execute();
    }

    public static void main(String[] args) {

        //final HttpRequest request = HttpUtil.createPost("https://newapprerorder.jiuxian.com/reservation/addorder.htm");
        //request.body(URLEncoder.createQuery().encode("apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=2707&channelCode=0,1&cityName=上海市&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.3627880859375&longi=121.5511895073785&netEnv=unkown&orderAddInfo={\"reservationToken\":\"\",\"toUseCashBack\":\"0\",\"orderDelivery\":[],\"couponId\":\"\",\"isBuyImmediately\":\"1\",\"payType\":\"1\",\"toUseAllowance\":\"0\",\"coldNum\":0,\"toUseCoupon\":\"0\",\"invType\":\"0\",\"invTitle\":\"\",\"productId\":\"626626\",\"invMobile\":\"18521057139\",\"stockoutGifts\":\"\",\"isGiftOrder\":\"0\",\"isReservation\":1,\"buyNum\":\"1\",\"invContent\":\"\",\"deliveryId\":\"16\",\"invKind\":\"0\"}&pushToken=&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token=d8f8d47e5d7940d6ab49007458c42df5129868384", CHARSET_UTF_8));
        //HttpResponse response1 = request.execute();

        final long productId = 626626;
        JiuxianService jiuxianService = new JiuxianService();
        // 18701961952  Xq1831833
        // 18521057139  J1qazxsw2
        HttpResponse loginResponse = jiuxianService.login("18521057139", "J1qazxsw2");

        JSONObject loginJson = JSON.parseObject(loginResponse.body());
        if (loginJson.getIntValue("success") != 1) {
            System.out.println(loginJson.getString("errMsg"));
            return;
        }
        JSONObject result = (JSONObject) loginJson.get("result");
        JSONObject userInfo = (JSONObject) result.get("userInfo");
        final String token = userInfo.getString("token");

        // 查询收获地址
        HttpResponse addressResponse = jiuxianService.getAddress(token);
        JSONObject addressJson = JSON.parseObject(addressResponse.body());
        JSONArray addressList = (JSONArray) ((JSONObject) addressJson.get("result")).get("addrList");
        JSONObject addressObj = new JSONObject();
        if (addressList.size() > 0) {
            addressObj = ((JSONObject) addressList.get(0));
        }

        // {"result":{"userInfo":{"apiVersion":1.0,"areaId":500,"channelCode":"0","isClubUser":true,"isNewUser":false,"loginUnionFirst":0,"loginWay":3,"mobile":"18521057139","needBindMobile":false,"rank":1,"rankName":"酒虫","sex":0,"token":"425ed50ddb4446d6983fae8b183e0f95129868384","uid":129868384,"uname":"jxw885572897","userImg":"https://misc.jiuxian.com/img/usercenter/sbbgg.jpg"}},"errCode":"","success":"1","errMsg":""}

        // apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=2707&channelCode=0%2C1&cityName=%E4%B8%8A%E6%B5%B7%E5%B8%82&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.3627880859375&longi=121.5511895073785&netEnv=unkown&orderAddInfo=%7B%22reservationToken%22%3A%22bc3ac82dc46a597ccd8f1392bb3a6459%22%2C%22toUseCashBack%22%3A%220%22%2C%22orderDelivery%22%3A%5B%5D%2C%22couponId%22%3A%22%22%2C%22isBuyImmediately%22%3A%221%22%2C%22payType%22%3A%221%22%2C%22toUseAllowance%22%3A%220%22%2C%22coldNum%22%3A0%2C%22toUseCoupon%22%3A%220%22%2C%22invType%22%3A%220%22%2C%22invTitle%22%3A%22%22%2C%22productId%22%3A%22626626%22%2C%22invMobile%22%3A%2218521057139%22%2C%22stockoutGifts%22%3A%22%22%2C%22isGiftOrder%22%3A%220%22%2C%22isReservation%22%3A1%2C%22buyNum%22%3A%221%22%2C%22invContent%22%3A%22%22%2C%22deliveryId%22%3A%2216%22%2C%22invKind%22%3A%220%22%7D&pushToken=1bc7ed4b0ea125318ab85a2a4376beca9631b887397ae0da1f8db63635653e84&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token=d8f8d47e5d7940d6ab49007458c42df5129868384
        // apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=2707&channelCode=0,1&cityName=上海市&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.3627880859375&longi=121.5511895073785&netEnv=unkown&orderAddInfo={"reservationToken":"bc3ac82dc46a597ccd8f1392bb3a6459","toUseCashBack":"0","orderDelivery":[],"couponId":"","isBuyImmediately":"1","payType":"1","toUseAllowance":"0","coldNum":0,"toUseCoupon":"0","invType":"0","invTitle":"","productId":"626626","invMobile":"18521057139","stockoutGifts":"","isGiftOrder":"0","isReservation":1,"buyNum":"1","invContent":"","deliveryId":"16","invKind":"0"}&pushToken=1bc7ed4b0ea125318ab85a2a4376beca9631b887397ae0da1f8db63635653e84&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token=d8f8d47e5d7940d6ab49007458c42df5129868384
        HttpResponse makeOrder;
        if (productId != 626626) {
            // 添加到购物车
            String query =
                "apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=" + addressObj.getLong("districtId")
                    + "&channelCode=0,1&cityName=上海市&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.31619411892361&longi=121.4094590928819&netEnv=unkown&orderSetInfo={\"toUseCoupon\":\"-1\",\"isGiftOrder\":\"-1\",\"productInfo\":{\"normalList\":[{\"productId\":\"626625\",\"buyNum\":\"1\"}]},\"isXinKe\":0,\"isBuyImmediately\":\"1\",\"isPresell\":0,\"invType\":\"0\",\"payType\":\"0\",\"invKind\":\"-1\",\"stockoutGifts\":\"\",\"toUseAllowance\":\"-1\",\"toUseCashBack\":\"1\",\"coldNum\":0,\"isReservation\":0}&pushToken=&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token="
                    + token;

            HttpResponse addResponse = jiuxianService.addCart(query);
            CommonUtil.log("添加购物车 %s", addResponse.getStatus());
            makeOrder = jiuxianService.makeOrder(
                "apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=" + addressObj.getLong("districtId")
                    + "&channelCode=0,1&cityName=上海市&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.31619411892361&longi=121.4094590928819&netEnv=unkown&orderAddInfo={\"toUseCoupon\":\"0\",\"invTitle\":\"\",\"couponId\":\"\",\"isGiftOrder\":\"0\",\"invMobile\":\"18521057139\",\"isBuyImmediately\":\"1\",\"addressId\":\""
                    + addressObj.getLong("addrId")
                    + "\",\"toUseCashBack\":\"0\",\"payType\":\"1\",\"invKind\":\"0\",\"invType\":\"0\",\"toUseAllowance\":\"0\",\"invContent\":\"\",\"deliveryId\":\"16\",\"userLeaveMessage\":\"test\",\"stockoutGifts\":\"\",\"coldNum\":0,\"orderDelivery\":[]}&pushToken=&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token="
                    + userInfo.getString("token"));
        } else {
            HttpResponse preResponse = jiuxianService.addPre("actId=983&apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=" + addressObj.getLong("districtId")
                + "&blackBox=eyJ0b2tlbklkIjoidzRkVXN2UlgwV2tCb2d2eHFZMHJ1bzhyazc5MllTZDZZS1wvN01haDlTNlowNTdReGJVY2gzeFwvSUh6WjBjdUM3ajR6VWRiRkhjZHJnSWo3NThoRzVMdz09Iiwib3MiOiJpT1MiLCJzZXFJZCI6IjE2NDMyNDg1Mjg4MDA3MTM1ODUiLCJwcm9maWxlVGltZSI6MzA2LCJ2ZXJzaW9uIjoiMy42LjQifQ%3D%3D&channel=1&channelCode=0%2C1&cityName=%E4%B8%8A%E6%B5%B7%E5%B8%82&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.35903103298611&longi=121.5362928602431&netEnv=unkown&productId="
                + productId
                + "&pushToken=1bc7ed4b0ea125318ab85a2a4376beca9631b887397ae0da1f8db63635653e84&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token=" + token);

            preResponse = jiuxianService.addPreOrder("actId=983&apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=" + addressObj.getLong("districtId")
                + "&channel=1&channelCode=0%2C1&cityName=%E4%B8%8A%E6%B5%B7%E5%B8%82&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.35903103298611&longi=121.5362928602431&netEnv=unkown&number=1&productId="
                + productId + "&pushToken=1bc7ed4b0ea125318ab85a2a4376beca9631b887397ae0da1f8db63635653e84&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token=" + token);

            makeOrder = jiuxianService.makeSpecialOrder(
                "apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=" + addressObj.getLong("districtId")
                    + "&channelCode=0,1&cityName=上海市&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.3627880859375&longi=121.5511895073785&netEnv=unkown&orderAddInfo={\"reservationToken\":\""+ jiuxian
                    .encode("ANDROIDBFE41A56-B351-4541-89E8-E0BA0D6BB29DBFE41A56-B351-4541-89E8-E0BA0D6BB29D")+"\",\"toUseCashBack\":\"0\",\"orderDelivery\":[],\"couponId\":\"\",\"isBuyImmediately\":\"1\",\"payType\":\"1\",\"toUseAllowance\":\"0\",\"coldNum\":0,\"toUseCoupon\":\"0\",\"invType\":\"0\",\"invTitle\":\"\",\"productId\":\"626626\",\"invMobile\":\"18521057139\",\"stockoutGifts\":\"\",\"isGiftOrder\":\"0\",\"isReservation\":1,\"buyNum\":\"1\",\"invContent\":\"\",\"deliveryId\":\"16\",\"invKind\":\"0\"}&pushToken=&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token="
                    + userInfo.getString("token"));
        }

        // {"result":{"backInfor":"您的订单已提交成功","locationAddressInfor":{"districtId":2717,"province":"上海","city":"上海市","district":"宝山区","cityId":321,"provinceId":25},"orderId":127666558,"orderPrice":408.00,"orderSn":"18220123020500931809","payName":"在线支付","payPrice":408.00,"payType":1},"errCode":"","success":"1","errMsg":""}

        System.out.println(makeOrder);
    }

}
